﻿using System;
using System.IO;
using Sasa.QualityTools.CodeAnalysis.Common;
using Sasa.QualityTools.CodeAnalysis.Core.Properties;

namespace Sasa.QualityTools.CodeAnalysis.Core.Models
{
    internal class RuleSetConverter
    {
        private string customDir;


        internal RuleSetConverter(string customDir)
        {
            this.customDir = customDir;
        }


        internal string Convert(string value)
        {
            if (String.IsNullOrWhiteSpace(value))
            {
                return null;
            }

            var dir = Path.GetDirectoryName(value);
            var fileName = Path.GetFileName(value);
            var bundleDir = Path.GetFullPath(Path.Combine(Environment.GetEnvironmentVariable("VS100COMNTOOLS"), "..", "..", "Team Tools", "Static Analysis Tools", "Rule Sets"));
            if (dir == bundleDir)
            {
                return "Bundled;" + fileName;
            }
            else if (dir == customDir)
            {
                return "Custom;" + fileName;
            }
            else
            {
                throw new InvalidOperationException(Text.Format(Resources.RuleSetPathIsInvalid, value));
            }
        }

        internal string Reverse(string value)
        {
            if (String.IsNullOrWhiteSpace(value) || !value.Contains(";"))
            {
                return null;
            }

            var tokens = value.Split(new string[] { ";" }, 2, StringSplitOptions.RemoveEmptyEntries);
            switch (tokens[0])
            {
                case "Bundled":
                    return Path.GetFullPath(Path.Combine(Environment.GetEnvironmentVariable("VS100COMNTOOLS"), "..", "..", "Team Tools", "Static Analysis Tools", "Rule Sets", tokens[1]));
                case "Custom":
                    return Path.Combine(customDir, tokens[1]);
                default:
                    throw new InvalidOperationException(Text.Format(Resources.RuleSetConfigValueIsInvalid, value));
            }
        }
    }
}
